
import CryptoTool from '@/utils/crypto/jscrypto.js'
import { app_channel } from '@/config/config.js'
const requestInterceptors=(vm)=>{
	/**
	 * 请求拦截
	 * @param {Object} http
	 */
	uni.$u.http.interceptors.request.use((config) => { 
		config.data = config.data || {}
		if (config.custom.show) {
			uni.$tools.showLoading(config.custom.title, config.custom.mask)
		}
		return config
	}, (config) => 
		Promise.reject(config))
}
const responseInterceptors=(vm)=>{
	/**
	 * 响应拦截
	 * @param {Object} http 
	 */
	uni.$u.http.interceptors.response.use((response) => { 
		// 自定义参数
		const custom = response.config?.custom
		if (custom.show) {
			uni.$tools.hideLoading()
		}
		let encryptData = response.data
		///解密结果字符串
		const decryptRes = CryptoTool.networkDecrypt(encryptData)
		///解密结果json
		const data = JSON.parse(decryptRes)
		if(process.env.VITE_ISLOG){
			console.log('请求结果：',data)
		}
		if (data.meta.statusCode != 200) {
			if (data.message.content) {
				uni.$tools.showToast(data.message.content)
			}
			if(data.message.code == 'E00401' || data.message.code == 'E11001'){
				uni.$auth.logout()
				uni.reLaunch({
					url:'/pages/login/login'
				})
				return Promise.reject('')
			}
			else{
				return Promise.reject(data)
			}
		}
		return data || {}
	}, (response) => { 
		uni.$tools.showToast('似乎与网络断开了连接~')
		return Promise.reject(response)
	})
}

//  初始化请求配置
const initRequest=(vm)=>{
	uni.$u.http.setConfig((defaultConfig) => {
		/* defaultConfig 为默认全局配置 */
		defaultConfig.baseURL = process.env.VITE_BASE_URL
		defaultConfig.header = {'Accept':'application/x-json;charset=utf-8','Content-Type':'application/x-json','channel':app_channel()}
		return defaultConfig
	})
	requestInterceptors()
	responseInterceptors()
}
export {
	initRequest
}